package com.yaodian100.ec.productlimitsale;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.generate.service.GenerateService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitMain;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitProd;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;

/**
 * 商品限制购买设定
 * 
 * @author apple.chang
 * 
 */
public class ProductLimitSaleAction extends ActionSupport implements Preparable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4361192705983283905L;

	// private final Logger logger = LoggerFactory.getLogger(ProductLimitSaleAction.class);
	private TimeLimitSaleService timeLimitSaleService;
	private DomainService<Menu> menuService;
	private GenerateService generateService;
	private ProductService productService;
	private ShelfService shelfService;
	private SimplePager pager = null;

	private List<TimeLimitProd> timeLimitProdList;
	private String id;
	private String minDate;
	private String productId;
	private String productName;
	private String startDate;
	private String endDate;
	private String startTime;
	private String endTime;
	private String result;
	private String limitPrice;

	/******* 查询页面参数 ********/
	private String spIdParam;
	private String snameParam;
	private Menu showTypeMenu;
	private Menu shelfStatusMenu;
	private String sstartDateParam;
	private String sendDateParam;
	private String sshowTypeParam;

	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		clearErrorsAndMessages();

		if (null == pager) {
			pager = new SimplePager();
		}

		if (null == showTypeMenu) {
			showTypeMenu = menuService.get("TimeLimitSale.ShowType");
		}
		if (null == shelfStatusMenu) {
			shelfStatusMenu = menuService.get("Shelf.Status");
		}
		minDate = DateUtil.convertDateToString("yyyy,MM - 1,dd", new Date());
	}

	public String search() throws ParseException {
		// search value
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("imagePath", "img_path");
		if (StringUtils.isNotBlank(spIdParam) && spIdParam.length() == 8) {
			crit.addRlike("productId", spIdParam);
		}
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		if (StringUtils.isNotBlank(sstartDateParam)) {
			crit.addGe("startDate", dateFormat.parse(sstartDateParam));
		}
		if (StringUtils.isNotBlank(sstartDateParam)) {
			crit.addGe("startDate", dateFormat.parse(sstartDateParam));
		}
		if (StringUtils.isNotBlank(sendDateParam)) {
			crit.addLe("endDate", dateFormat.parse(sendDateParam));
		}
		if (StringUtils.isNotBlank(sshowTypeParam)) {
			Date now = new Date();
			if (sshowTypeParam.equals("WAIT")) {
				crit.addGe("startDate", now);
			} else if (sshowTypeParam.equals("ON")) {
				crit.addLe("startDate", now);
				crit.addGe("endDate", now);
			} else if (sshowTypeParam.equals("OVERDUE")) {
				crit.addLe("endDate", now);
			}
		}
		int contentSize = timeLimitSaleService.getTimeLimitProdListSize(crit).intValue();
		pager.setPageRecord(20);
		pager.setTotalSize(contentSize);

		timeLimitProdList = timeLimitSaleService.getTimeLimitProdList(crit, new String[] { "startDate desc" }, pager
				.getCurrentPage()
				* pager.getPageRecord(), pager.getPageRecord());
		return "list";
	}

	public String add() {
		result = null;
		id = "";
		startDate = "";
		endDate = "";
		startTime = "";
		endTime = "";
		productName = "";
		limitPrice = "";
		productId = "";
		return "edit";
	}

	public String edit() {
		TimeLimitProd tlp = timeLimitSaleService.getTimeLimitProd(id);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		startDate = df.format(tlp.getStartDate());
		endDate = df.format(tlp.getEndDate());
		startTime = startDate.substring(11, 16);
		endTime = endDate.substring(11, 16);
		startDate = startDate.substring(0, 10);
		endDate = endDate.substring(0, 10);
		productName = tlp.getProductName();
		limitPrice = tlp.getLimitPrice().toString();
		productId = tlp.getProductId();
		return "edit";
	}

	public String save() throws ParseException, Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		TimeLimitProd tlp;
		if (StringUtils.isNotBlank(id)) {
			tlp = timeLimitSaleService.getTimeLimitProd(id);
		} else {
			TimeLimitMain tlm;
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("categoryID", -1);
			if (timeLimitSaleService.getListSize(criteria).intValue() > 0) {
				tlm = timeLimitSaleService.getList(0, -1, criteria, new String[] { "createDate desc" }).get(0);
			} else {
				tlm = new TimeLimitMain();
				tlm.setCategoryID(-1);
				tlm.setSaleDate(new Date());
				tlm.setName("一元秒杀");
				tlm = timeLimitSaleService.save(tlm);
			}
			tlp = new TimeLimitProd();
			tlp.setMainId(tlm.getId());
		}
		tlp.setStartDate(df.parse(startDate + " " + startTime + ":00"));
		tlp.setEndDate(df.parse(endDate + " " + endTime + ":59"));
		tlp.setProductId(productId);
		tlp.setLimitPrice(new BigDecimal(limitPrice));
		tlp.setMemberPrice(new BigDecimal(limitPrice));
		tlp.setProductName(StringUtils.substring(productName, 0, 40));
		tlp.setIdxProductName("一元秒杀商品");
		tlp.setImagePath("img_path");
		tlp.setIsLimitBuy("Y");
		tlp.setIsRepeat("N");
		tlp = timeLimitSaleService.saveOrUpdateTimeLimitProd(tlp);
		id = tlp.getId().toString();
		DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		timeLimitSaleService.updateData(df2.format(new Date()));
		addFieldError("", "储存成功");
		return "edit";
	}

	/**
	 * 查询商品是否可上广告
	 * 
	 * @return
	 * @throws Exception
	 */
	public String findProductShelf() {
		result = "";
		if (StringUtils.isNotBlank(productId)) {
			if (startDate.length() != 16 || endDate.length() != 16) {
				result = "timeError";
				return "jsonFindProductShelf";
			}
			Product p = productService.get(productId);
			if (null == p) {
				result = "商品编号错误";
				return "jsonFindProductShelf";
			}
			StringBuffer sb = new StringBuffer();
			CommonCriteria crit = new CommonCriteria();
			crit.addEq("productId", productId);
			crit.addEq("isDelete", "N");
			List<Specification> specifications = productService.getSpecificationList(0, -1, crit, new String[] {
					"showSeq asc", "modifyDate desc" });
			Map<String, SpecificationInventory> simap = productService.getSpecificationInventoryMap(productId);
			if (null != specifications && specifications.size() > 0) {
				sb.append("<a href='" + ServerValue.getMidContextPath() + "/product/spec.do?productId=" + productId
						+ "' target='_blank'>维护规格</a><br/>");
				sb.append("<table><thead><tr><th>规格名称</th><th>最大购买数</th><th>最小购买数</th><th>可售数</th></tr></thead><tbody>");
				for (Specification spec : specifications) {
					SpecificationInventory sp = simap.get(spec.getSpecificationId().toString());

					sb.append("<tr><td>").append(sp.getSpecification().getSpecificationName()).append("</td><td>").append(
							sp.getSpecification().getMaxCountPerOrder()).append("</td><td>").append(
							sp.getSpecification().getMinCountPerOrder()).append("</td><td>").append(
							(sp.getAvailableInventory() - sp.getSoldInventory() + sp.getCancelInventory())).append("</td></tr>");
				}
				sb.append("</tbody></table><br/>");
			}

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Shelf shelf;
			try {
				shelf = shelfService.getShelfByProductId(productId, df.parse(startDate), df.parse(endDate));
			} catch (Exception e) {
				result = "timeError";
				return "jsonFindProductShelf";
			}
			// 查上架檔
			if (p.getProductType() == 6) {
				sb.append("<a href='" + ServerValue.getMidContextPath() + "/pickProduct/editShelf.do?productIdParam="
						+ productId + "' target='_blank'>维护上架档</a><br/>");
			} else {
				sb.append("<a href='" + ServerValue.getMidContextPath() + "/shelf/list.do?productId=" + productId
						+ "' target='_blank'>维护上架档</a><br/>");
			}
			if (null == shelf) {
				sb.append("查无上架档<br/>");
				result = sb.toString();
				return "jsonFindProductShelf";
			} else {
				sb.append("商品编号:").append(productId).append("<br/>");
				sb.append("起始时间:").append(df.format(shelf.getStartDate())).append("<br/>");
				sb.append("结束时间:").append(df.format(shelf.getEndDate())).append("<br/>");
				sb.append("售价:").append("<font color='red'>" + shelf.getShelfPrice().toString()).append("</font><br/>");
				sb.append("上架状态:").append(shelfStatusMenu.getOptions().get(shelf.getShelfStatus()).getName()).append("<br/>");
			}
			result = sb.toString();
		}
		return "jsonFindProductShelf";
	}

	public TimeLimitSaleService getTimeLimitSaleService() {
		return timeLimitSaleService;
	}

	public void setTimeLimitSaleService(TimeLimitSaleService timeLimitSaleService) {
		this.timeLimitSaleService = timeLimitSaleService;
	}

	public DomainService<Menu> getMenuService() {
		return menuService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public SimplePager getPager() {
		return pager;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public List<TimeLimitProd> getTimeLimitProdList() {
		return timeLimitProdList;
	}

	public void setTimeLimitProdList(List<TimeLimitProd> timeLimitProdList) {
		this.timeLimitProdList = timeLimitProdList;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getMinDate() {
		return minDate;
	}

	public void setMinDate(String minDate) {
		this.minDate = minDate;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public Menu getShowTypeMenu() {
		return showTypeMenu;
	}

	public void setShowTypeMenu(Menu showTypeMenu) {
		this.showTypeMenu = showTypeMenu;
	}

	public String getSstartDateParam() {
		return sstartDateParam;
	}

	public void setSstartDateParam(String sstartDateParam) {
		this.sstartDateParam = sstartDateParam;
	}

	public String getSendDateParam() {
		return sendDateParam;
	}

	public void setSendDateParam(String sendDateParam) {
		this.sendDateParam = sendDateParam;
	}

	public String getSshowTypeParam() {
		return sshowTypeParam;
	}

	public void setSshowTypeParam(String sshowTypeParam) {
		this.sshowTypeParam = sshowTypeParam;
	}

	public String getSnameParam() {
		return snameParam;
	}

	public void setSnameParam(String snameParam) {
		this.snameParam = snameParam;
	}

	public GenerateService getGenerateService() {
		return generateService;
	}

	public void setGenerateService(GenerateService generateService) {
		this.generateService = generateService;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public ShelfService getShelfService() {
		return shelfService;
	}

	public void setShelfService(ShelfService shelfService) {
		this.shelfService = shelfService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String getLimitPrice() {
		return limitPrice;
	}

	public void setLimitPrice(String limitPrice) {
		this.limitPrice = limitPrice;
	}

	public String getSpIdParam() {
		return spIdParam;
	}

	public void setSpIdParam(String spIdParam) {
		this.spIdParam = spIdParam;
	}

}